<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">编辑商家信息</text>
    </view>

    <!-- 商家信息表单 -->
    <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-position="top" class="form" label-width="200">
      <uni-forms-item label="商家名称" name="name" required>
        <uni-easyinput v-model="formData.name" placeholder="请输入商家名称" />
      </uni-forms-item>

      <uni-forms-item label="联系电话" name="phone" required>
        <uni-easyinput v-model="formData.phone" type="tel" placeholder="请输入联系电话" />
      </uni-forms-item>

      <uni-forms-item label="商家位置 (地图选点)" name="location" required>
        <view class="location-select" @click="chooseLocation">
          <text v-if="formData.latitude && formData.longitude">
            已选择: {{ formData.latitude.toFixed(6) }}, {{ formData.longitude.toFixed(6) }}
          </text>
          <text v-else class="select-location-text">点击选择位置</text>
        </view>
      </uni-forms-item>

      <uni-forms-item label="商家地址" name="address" required>
        <uni-easyinput v-model="formData.address" placeholder="请输入商家地址" />
      </uni-forms-item>

      <uni-forms-item label="商家Logo" name="logo" required>
        <uni-file-picker v-model="formData.logo" file-mediatype="image" limit="1" :auto-upload="false" @select="e => handleImageSelect(e, 'logo')" />
      </uni-forms-item>

      <uni-forms-item label="所属食堂" name="canteenId">
        <uni-data-select v-model="formData.canteenId" :localdata="formattedCanteenList" placeholder="请选择食堂" />
      </uni-forms-item>

      <uni-forms-item label="商户分类" name="categoryIds" required>
        <uni-data-select v-model="formData.categoryIds[0]" :localdata="formattedCategoryList" placeholder="请选择分类" />
      </uni-forms-item>

      <uni-forms-item label="备餐时长（分钟）" name="baseTime" required>
        <uni-easyinput v-model.number="formData.baseTime" type="number" placeholder="请输入备餐时长" />
      </uni-forms-item>

      <uni-forms-item label="配送费（元）" name="deliveryFee" required>
        <uni-easyinput v-model.number="formData.deliveryFee" type="digit" placeholder="请输入配送费" />
      </uni-forms-item>

      <uni-forms-item label="起送价（元）" name="minPrice" required>
        <uni-easyinput v-model.number="formData.minPrice" type="digit" placeholder="请输入起送价" />
      </uni-forms-item>

      <uni-forms-item label="营业执照图片" name="licenseImage" required>
        <uni-file-picker v-model="formData.licenseImage" file-mediatype="image" limit="1" :auto-upload="false" @select="e => handleImageSelect(e, 'licenseImage')" />
      </uni-forms-item>

      <uni-forms-item label="店内照片 (最多6张)" name="shopImageList" required>
        <uni-file-picker v-model="formData.shopImageList" file-mediatype="image" limit="6" :auto-upload="false" multiple @select="e => handleImageSelect(e, 'shopImageList')" />
      </uni-forms-item>

      <uni-forms-item label="商户描述" name="description">
        <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入商户描述" :autoHeight="true" style="min-height: 120px;" />
      </uni-forms-item>

      <uni-forms-item label="支持外卖配送" name="supportDelivery">
        <switch :checked="formData.supportDelivery === 1" @change="e => formData.supportDelivery = e.detail.value ? 1 : 0" />
      </uni-forms-item>

      <uni-forms-item label="支持堂食" name="supportDineIn">
        <switch :checked="formData.supportDineIn === 1" @change="e => formData.supportDineIn = e.detail.value ? 1 : 0" />
      </uni-forms-item>

      <uni-forms-item label="支持自取" name="supportTakeout">
        <switch :checked="formData.supportTakeout === 1" @change="e => formData.supportTakeout = e.detail.value ? 1 : 0" />
      </uni-forms-item>

      <button class="save-btn" @click="saveInfo">保存修改</button>
    </uni-forms>
  </view>
</template>

<script setup>
import { ref, onUnmounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getMerchantId } from '@/utils/merchant.js';
import { getMerchantInfo, updateMerchantInfo, getCategoryList } from '@/api/merchant';
import { uploadToOSS, fetchAndScheduleStsToken, clearStsTokenTimer } from '@/utils/oss';
import { getCanteenList } from '@/api/user';
import { useUserStore } from '@/store/user';

const formRef = ref(null);
const canteenList = ref([]);
const categoryList = ref([]);
const userStore = useUserStore();

const formData = ref({
  id: '',
  name: '',
  phone: '',
  address: '',
  logo: [],
  latitude: '',
  longitude: '',
  canteenId: '',
  baseTime: '',
  minPrice: '',
  deliveryFee: '',
  licenseImage: [],
  shopImageList: [],
  description: '',
  supportDelivery: 1,
  supportDineIn: 1,
  supportTakeout: 1,
  categoryIds: []
});

const rules = ref({
  name: { rules: [{ required: true, errorMessage: '请输入商家名称' }] },
  phone: {
    rules: [
      { required: true, errorMessage: '请输入联系电话' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号码' }
    ]
  },
  address: { rules: [{ required: true, errorMessage: '请输入商家地址' }] },
  location: { // Custom validation for latitude/longitude
    rules: [{
      validateFunction: (rule, value, data, callback) => {
        if (!data.latitude || !data.longitude) {
          callback('请选择商家位置');
        }
        return true;
      }
    }]
  },
  logo: { rules: [{ required: true, errorMessage: '请上传商家Logo' }] },
  baseTime: { 
    rules: [
      { required: true, errorMessage: '请输入备餐时长' },
      { type: 'number', errorMessage: '备餐时长必须是数字' },
      { minimum: 1, errorMessage: '备餐时长不能小于1分钟' }
    ]
  },
  minPrice: { 
    rules: [
      { required: true, errorMessage: '请输入起送价' },
      { type: 'number', errorMessage: '起送价必须是数字' },
      { minimum: 0, errorMessage: '起送价不能为负' },
      {
        validateFunction: (rule, value, data, callback) => {
          const deliveryFee = parseFloat(data.deliveryFee) || 0;
          const minPrice = parseFloat(value) || 0;
          const deliveryFeeRatio = userStore.deliveryFeeRatio || 0;
          
          if (deliveryFee > 0 && deliveryFeeRatio > 0) {
            const requiredMinOrderAmount = deliveryFee * deliveryFeeRatio; // 订单最低实付金额
            const requiredMinPrice = requiredMinOrderAmount - deliveryFee; // 起送价最低限制
            if (minPrice < requiredMinPrice) {
              const ceiledMinPrice = Math.ceil(requiredMinPrice * 100) / 100;
              callback(`起送价不能低于${ceiledMinPrice.toFixed(2)}元（受配送费影响），以确保微信分账成功`);
            }
          }
          return true;
        }
      }
    ]
  },
  deliveryFee: { 
    rules: [
      { required: true, errorMessage: '请输入配送费' },
      { type: 'number', errorMessage: '配送费必须是数字' },
      { minimum: 0, errorMessage: '配送费不能为负' }
    ]
  },
  categoryIds: { rules: [{ required: true, errorMessage: '请选择商户分类' }] },
  licenseImage: { rules: [{ required: true, errorMessage: '请上传营业执照图片' }] },
  shopImageList: {
    rules: [{
      validateFunction: (rule, value, data, callback) => {
        if (!data.shopImageList || data.shopImageList.length === 0) {
          callback('请上传店内照片');
        }
        if (data.shopImageList && data.shopImageList.length > 6) {
          callback('店内照片最多上传6张');
        }
        return true;
      }
    }]
  }
  // canteenId, description, supportDelivery, supportDineIn, supportTakeout are optional or have default values
});

const formattedCanteenList = computed(() => {
  return canteenList.value.map(c => ({ value: c.id, text: c.name }));
});

const formattedCategoryList = computed(() => {
  return categoryList.value.map(c => ({ value: c.id, text: c.name }));
});

onLoad(async () => {
  const merchantId = getMerchantId();
  if (!merchantId) {
    uni.showToast({ title: '未获取到商家ID', icon: 'none' });
    return;
  }
  try {
    const { data } = await getMerchantInfo(merchantId);
    formData.value = {
      id: data.id || '',
      name: data.name || '',
      phone: data.phone || '',
      address: data.address || '',
      logo: data.logo || '',
      latitude: data.latitude || '',
      longitude: data.longitude || '',
      canteenId: data.canteenId || '',
      baseTime: data.baseTime || '',
      minPrice: data.minPrice || '',
      deliveryFee: data.deliveryFee || '',
      licenseImage: data.licenseImage || '',
      shopImageList: data.shopImage ? (typeof data.shopImage === 'string' ? data.shopImage.split(',') : data.shopImage) : [],
      description: data.description || '',
      supportDelivery: data.supportDelivery ?? 1,
      supportDineIn: data.supportDineIn ?? 1,
      supportTakeout: data.supportTakeout ?? 1,
      categoryIds: data.categoryIds || []
    };
    if (formData.value.logo && typeof formData.value.logo === 'string') {
      formData.value.logo = [{ url: formData.value.logo }];
    } else if (!formData.value.logo) {
      formData.value.logo = [];
    }
    if (formData.value.licenseImage && typeof formData.value.licenseImage === 'string') {
      formData.value.licenseImage = [{ url: formData.value.licenseImage }];
    } else if (!formData.value.licenseImage) {
      formData.value.licenseImage = [];
    }
    formData.value.shopImageList = formData.value.shopImageList.map(img => ({ url: img }));

    await fetchAndScheduleStsToken();
    const canteenRes = await getCanteenList();
    canteenList.value = canteenRes.data || [];
    
    const categoryRes = await getCategoryList();
    categoryList.value = categoryRes.data || [];
  } catch (error) {
    console.error('Failed to load merchant info, canteen list or category list:', error);
    uni.showToast({ title: '加载信息失败', icon: 'none' });
  }
});


function handleImageSelect(e, field) {
  // 参考商品编辑页图片上传逻辑
  const files = e.tempFiles || e.detail.tempFiles || [];
  if (!files.length) return;
  uni.showLoading({ title: '上传中...' });
  const uploadPromises = files.map(file => uploadToOSS(file.url, `merchant/${field}`));
  Promise.all(uploadPromises)
    .then(urls => {
      if (field === 'shopImageList') {
        const imageUrls = urls.map(url => ({ url }));
        formData.value.shopImageList = [...formData.value.shopImageList, ...imageUrls];
      } else {
        formData.value[field] = [{ url: urls[0] }];
      }
      uni.showToast({ title: '上传成功', icon: 'success' });
    })
    .catch(err => {
      console.error('上传失败', err);
      uni.showToast({ title: '上传失败', icon: 'none' });
    })
    .finally(() => {
      uni.hideLoading();
    });
}



onUnmounted(() => {
  clearStsTokenTimer();
});

const chooseLocation = async () => {
  try {
    // 获取用户授权设置
    const settingRes = await uni.getSetting();
    
    // 检查是否有位置权限
    if (!settingRes.authSetting['scope.userLocation']) {
      // 如果没有授权，则请求授权
      try {
        await uni.authorize({ scope: 'scope.userLocation' });
        // 授权成功会进入这里，不需要再次检查 authSetting
      } catch (authErr) {
        // 授权失败，提示用户去设置页面开启权限
        uni.showModal({
          title: '权限提示',
          content: '需要位置权限才能选择地址，是否去设置开启？',
          confirmText: '去设置',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting({
                success: (settingRes) => {
                  if (settingRes.authSetting['scope.userLocation']) {
                    uni.showToast({ title: '权限已开启，请重试', icon: 'none' });
                  } else {
                    uni.showToast({ title: '仍未开启权限', icon: 'none' });
                  }
                }
              });
            }
          }
        });
        return; // 终止后续操作
      }
    }
    
    // 已有权限或已成功授权，调用选择位置API
    const locationRes = await uni.chooseLocation({}); 
    formData.value.address = locationRes.address;
    formData.value.latitude = locationRes.latitude;
    formData.value.longitude = locationRes.longitude;
  } catch (err) {
    if (err.errMsg && err.errMsg.includes('chooseLocation:fail cancel')) {
      // 用户取消选择位置，不做处理
    } else {
      console.error('Location choose error:', err);
      uni.showToast({
        title: `定位失败：${err.errMsg || '未知错误'}`, 
        icon: 'none',
        duration: 3000
      });
    }
  }
};

async function saveInfo() {
  try {
    // 表单校验阶段
    try {
    console.log("formRef===", formRef.value)
      const valid = await formRef.value.validate();
      if (!valid) return;
    } catch (validationError) {
      uni.showToast({ title: '表单校验失败：' + (validationError?.message || '请检查必填项'), icon: 'none' });
      return;
    }

    // 数据处理阶段
    const payload = { ...formData.value };
    payload.baseTime = parseFloat(payload.baseTime) || 0;
    payload.minPrice = parseFloat(payload.minPrice) || 0;
    payload.deliveryFee = parseFloat(payload.deliveryFee) || 0;
    // categoryIds需要传数组
    console.log("payload.categoryIds===", typeof payload.categoryIds)
    if (typeof payload.categoryIds === 'number') {
      payload.categoryIds = [payload.categoryIds];
      // payload.categoryIds = payload.categoryIds.split(',').map(id => parseInt(id));
    }
    // payload.shopImage = payload.shopImageList.join(',');

    // 若image为数组，取第一个元素作为提交参数
    if (Array.isArray(payload.logo)) {
      payload.logo = payload.logo[0].url || '';
    }
    if (Array.isArray(payload.licenseImage)) {
      payload.licenseImage = payload.licenseImage[0].url || '';
    }
    payload.shopImage = payload.shopImageList.map(img => img.url).join(',');

    // 接口调用阶段
    await updateMerchantInfo(payload);
    
    uni.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      const pages = getCurrentPages();
      pages.length > 1 ? uni.navigateBack() : uni.switchTab({ url: '/pages/index/index' });
    }, 1000);

  } catch (saveError) {
    console.error('保存失败:', saveError);
    uni.showToast({ 
      title: '保存失败：' + (saveError?.message || '请稍后重试'),
      icon: 'none',
      duration: 3000
    });
  }
}

</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f9f9f9;
}

.header {
  text-align: center;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
  .title {
    font-size: 36rpx;
    font-weight: bold;
  }
}

.form {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

// uni-forms-item will add its own spacing, adjust if needed
::v-deep .uni-forms-item {
  margin-bottom: 30rpx; 
}

.location-select {
  padding: 20rpx;
  border: 1px solid #e5e5e5;
  border-radius: 8rpx;
  text-align: center;
  color: #333;
  cursor: pointer;
  .select-location-text {
    color: #999;
  }
}

.logo-upload {
  width: 200rpx;
  height: 200rpx;
  border: 1px dashed #d9d9d9;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  .logo-preview {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
  }
  .upload-text {
    color: #999;
    font-size: 24rpx;
  }
}

.upload-btn {
  margin-bottom: 20rpx;
  background-color: #007aff !important; // Ensure uni-app button styles are overridden if needed
  color: white !important;
  font-size: 28rpx;
  padding: 10rpx 30rpx;
  border-radius: 8rpx;
  &:active {
    background-color: #005bb5 !important;
  }
}

.preview-img {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  margin-right: 10rpx; // For multiple images in a row
  margin-bottom: 10rpx;
  border: 1px solid #eee;
}

.img-list {
  display: flex;
  flex-wrap: wrap;
  .img-item {
    position: relative;
    margin-right: 10rpx;
    margin-bottom: 10rpx;
    .preview-img {
      width: 150rpx;
      height: 150rpx;
      border-radius: 8rpx;
    }
    .remove-img {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      background-color: red;
      color: white;
      border-radius: 50%;
      width: 36rpx;
      height: 36rpx;
      text-align: center;
      line-height: 36rpx;
      font-size: 28rpx;
      cursor: pointer;
      z-index: 1;
    }
  }
}

// Custom picker style if uni-data-select default is not preferred
// For uni-data-select, styling might be through its props or ::v-deep

.save-btn {
  margin-top: 40rpx;
  background-color: #4cd964;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  padding: 20rpx 0;
  &:active {
    background-color: #36a347;
  }
}

// Styles for switch if needed, uni-forms-item handles label and spacing
::v-deep .uni-forms-item__label {
  // font-weight: bold; // Example: make labels bold
}

::v-deep .uni-easyinput__content, ::v-deep .uni-easyinput__content-textarea {
  // Custom styles for input fields if needed
}

</style>


